package edu.stanford.bmir.protege.web.client.ui.ontology.transform;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;

import edu.stanford.bmir.protege.web.server.filesubmission.FileUploadConstants;
import edu.stanford.bmir.protege.web.server.transform.service.StringWord;
import edu.stanford.bmir.protege.web.shared.transform.UploadBean;


public class FileUploadServlert extends HttpServlet {
	
    public static final long DEFAULT_MAX_FILE_SIZE = Long.MAX_VALUE;
    
    private final File uploadsDirectory = FileUploadConstants.UPLOADS_DIRECTORY;
    
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory); 
		
		UploadBean ub = new UploadBean();
		//设置一下上传的IRI 以保证后续进行添加时IRI的改变
		String IRI = req.getParameter("IRI");
		if(StringUtils.isNotBlank(IRI)&&IRI.startsWith("http://")&&!"http://".equals(IRI)){
			StringWord.BASEURL = IRI;
			System.out.println(IRI);
		} else{
			//如果没有设置IRI则将该值进行初始化为原始的
			StringWord.BASEURL = "http://webprotege.stanford.edu/";
		}
		List items = null;   
		
		try {      
            items = upload.parseRequest(req);       
        }  
        catch (FileUploadException ex) {       
            ex.printStackTrace();       
        }      
      
        Iterator iter = items.iterator();       
        
        while (iter.hasNext()) {       
        	
            FileItem item = (FileItem) iter.next(); 
            
            String name = item.getFieldName();
            
            if ( "type".equals(name) ) {
            	String value = item.getString();
            	ub.setType(value);
            }
            if ( "fileName".equals( name ) ) {
            	String value = item.getString();
            	ub.setFileName(value);
            }
            if ( "file".equals( name ) ) {
            	ub.setInput(item.getInputStream());
            }
            
        } 
        
        String name = ub.getFileName()+"."+ub.getType();
        
        String filePath = uploadsDirectory.getAbsolutePath()+File.separator + name;
        
        System.out.println( filePath );
        
        File file = new File ( filePath );
        
        InputStream input = ub.getInput();
        FileUtils.copyInputStreamToFile(input, file);
//        if(!file.exists()) {
//        	file.mkdirs();
//            file.createNewFile();
//        }
//        FileOutputStream out=new FileOutputStream(file);
//        int c;
//        byte buffer[]=new byte[1024];
//        while((c=input.read(buffer))!=-1){
//            for(int i=0;i<c;i++)
//                out.write(buffer[i]);        
//        }
//        out.close();
//        input.close();
        IOUtils.closeQuietly(input);
        sendSuccessMessage( resp,name );
        
	}
	
	private void sendSuccessMessage(HttpServletResponse response, String fileName) throws IOException {
        PrintWriter writer = response.getWriter();
        writer.print( fileName );
        writer.flush();
    }
	
}
